<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="1">
        <div id="chat" class="main_main">
          <el-form ref="form" :model="formData" :rules="rules" :inline="true">
            <el-form-item label="收款单号" prop="code">
              <CodeRuleInput :band-value.sync="formData.code" table-name="finance_other_in_receipt" column-name="code" :is-edit="id" />
            </el-form-item>
            <el-form-item label="制单人员">
              <el-input v-model="formData.receiptByName" clearable placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="制单日期">
              <el-date-picker
                v-model="formData.receiptTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="收款方" prop="payee">
              <el-input v-model="formData.payee" clearable placeholder="请输入" />
            </el-form-item>
            <el-form-item label="收款类型">
              <DictSelect
                :band-value.sync="formData.incomeTypeCode"
                dict-type="incomeTypeCode"
              />
            </el-form-item>
            <el-form-item label="销售订单" class="clickChoose">
              <el-input v-model="formData.saleOrderCode" clearable placeholder="请选择" readonly />
              <a
                class="clickChoose_button"
                @click.prevent="chooseOrders"
              >
                <svg-icon icon-class="选择弹框" />
              </a>
            </el-form-item>
            <el-form-item label="含税总金额">
              <el-input v-model="formData.taxAllPrice" clearable placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="订单附件" class="double">
              <FileManageFull
                :file-names="formData.orderFileName"
                :file-real-names="formData.orderFileRealName"
                :file-urls="formData.orderUrl"
                :row-index="1"
                :readonly="true"
                @fileName="setFileName"
              />
            </el-form-item>
            <el-form-item label="附件" class="double">
              <FileManageFull
                :file-names="formData.fileName"
                :file-real-names="formData.fileRealName"
                :file-urls="formData.fileUrl"
                :row-index="1"
                @fileName="setFileName2"
              />
            </el-form-item>
            <!--            <el-table-column label="收款时间" min-width="200" prop="otherInTime" :show-overflow-tooltip="true">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-date-picker-->
            <!--                  v-model="scope.row.otherInTime"-->
            <!--                  type="datetime"-->
            <!--                  value-format="yyyy-MM-dd HH:mm"-->
            <!--                  format="yyyy-MM-dd HH:mm"-->
            <!--                  placeholder="请选择"-->
            <!--                  :editable="false"-->
            <!--                />-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-form-item label="备注" class="double">
              <el-input
                v-model="formData.remark"
                clearable
                type="textarea"
                maxlength="200"
                show-word-limit
                placeholder="请输入"
              />
            </el-form-item>
          </el-form>
          <div class="formItem_header">
            <!-- 订单明细 -->
            <div />
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="addRow">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteRow">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>
          <div
            ref="table_container"
            class="table_container draggableTable "
          >
            <el-table
              ref="table"
              :data="listData"
              stripe
              border
              style="width: 99.9%;"
              :cell-class-name="cellClassName"
              :header-cell-class-name="headerCellClassName"
              :row-class-name="rowClassName"
              :summary-method="getSummaries"
              :show-summary="true"
              @selection-change="selectionChange"
            >
              <el-table-column type="selection" width="70" align="center" />
              <el-table-column label="状态" min-width="80" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div v-if="scope.row.status=='2'" class="adequate_space">
                    <span>全部收款</span>
                  </div>
                  <div v-if="scope.row.status=='1'" class="under_execution">
                    <span>部分收款</span>
                  </div>
                  <div v-if="scope.row.status=='0'" class="pending_payment">
                    <span>待收款</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="收入名称" min-width="140" prop="incomeName">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.incomeName" clearable placeholder="请输入" clearable />
                </template>
              </el-table-column>
              <el-table-column label="附加收款金额" min-width="140" prop="otherIncomePrice">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.otherIncomePrice" clearable type="number" placeholder="请输入" clearable @input="change_otherIncomePrice(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="税额" min-width="140" prop="tax">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.tax" clearable type="number" placeholder="请输入" clearable @input="change_tax(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="未税金额" min-width="140" prop="unTax">
                <template slot-scope="scope">
                  <span>{{ scope.row.unTax }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="附件"
                min-width="130"
              >
                <template slot-scope="scope">
                  <FileManage
                    :file-names.sync="scope.row.fileName"
                    :file-real-names.sync="scope.row.fileRealName"
                    :file-urls.sync="scope.row.fileUrl"
                    :row-index="scope.$index"
                    @fileName="setFileName3"
                  />
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="140">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" clearable placeholder="请输入" clearable />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="100">
                <template slot-scope="scope">
                  <div class="blueColor" @click="payOrder(scope.row,scope.$index)">跟进收款</div>
                </template>
              </el-table-column>
              <el-table-column label="已收款" min-width="140" prop="hasPrice" />
              <el-table-column label="未收款" min-width="140" prop="unPrice" />
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="客户开票信息" name="0">
        <div class="main_main customer_info">
          <el-form :model="formData" :inline="true">
            <el-form-item label="名称">
              <el-input v-model="formData.accountName" clearable disabled />
            </el-form-item>
            <el-form-item label="纳税人识别号">
              <el-input v-model="formData.taxpayerNumber" clearable disabled />
            </el-form-item>
            <el-form-item label="开户行">
              <el-input v-model="formData.accountBank" clearable disabled />
            </el-form-item>
            <el-form-item label="账号">
              <el-input v-model="formData.accountNumber" clearable disabled />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="formData.invoicePhone" clearable disabled />
            </el-form-item>
            <el-form-item class=" double" label="地址">
              <el-input v-model="formData.invoiceAddress" clearable type="textarea" disabled />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="main_bottom" :class="id?'':'main_bottom_add'">
      <div v-if="id" class="main_bottom_delete">
        <el-button v-if="isEdit" type="reject" @click.stop="deleteOne">删除</el-button>
        <div v-else class="isReject">删除</div>
      </div>
      <div>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button @click.stop="onSubmit()">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, remove } from '@/api/receivableAndPayable/receivableAndPayableManage/additionalReceipt'
import moment from 'moment'
import followPay from './followPay.vue'
import Big from 'big.js'
import chooseOrder from './chooseOrder'
import { getDictSelects } from '@/api/common/common'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    resData: {}
  },
  data() {
    return {
      activeName: '1',
      formData: {
        id: '',
        code: '',
        receiptByName: '',
        receiptBy: '',
        receiptTime: '',
        payee: '',
        incomeTypeCode: '',
        saleOrderId: '',
        saleOrderCode: '',
        taxAllPrice: '',
        hasReceiptPrice: '',
        unReceiptPrice: '',
        hasPrice: '',
        unPrice: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        orderFileName: '',
        orderFileRealName: '',
        orderUrl: '',
        remark: '',
        accountName: '暂无',
        taxpayerNumber: '暂无',
        accountBank: '暂无',
        accountNumber: '暂无',
        invoicePhone: '暂无',
        invoiceAddress: '暂无',
        details: []
      },
      mainId: 'id', // 表格行ID
      tableHeight: '200',
      selectionsAll: [], // 表格所有页选中的行
      currentIndex: 0,
      loading: true,
      isEdit: true, // 删除权限
      listData: [],
      taxRateCodeList: [],
      rules: {
        payee: [
          { required: true, message: '收款方不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '收款单号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    listData: {
      handler(newVal, oldVal) {
        this.updateHasPrice(newVal)
      },
      deep: true
    }
  },
  created() {
    this.getDictOptions()
    if (!this.id) { // 没有id就是新增
      this.loading = false
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.receiptByName = this.$store.state.user.name
    this.formData.receiptBy = this.$store.state.user.userId
    this.formData.receiptTime = moment(new Date()).format('YYYY-MM-DD')
    const newData = this.$store.state.user.permissions // 看有没有删除权限
    this.isEdit = newData.includes('finance:otherOut:delete')
  },
  methods: {
    getUnTax(row, e) {
      console.log('e', e)
      if (row.otherIncomePrice > 0) {
        row.unPrice = Number(row.otherIncomePrice) - Number(row.hasPrice)
      }
      if (row.otherIncomePrice > 0 && row.tax > 0) {
        row.unTax = Number(row.otherIncomePrice) - Number(row.tax)
      }
      if (!e) {
        row.unTax = row.otherIncomePrice
        row.unPrice = row.otherIncomePrice
      }
    },
    change_otherIncomePrice(row) {
      if (row.tax > 0) {
        row.unTax = Number(row.otherIncomePrice) - Number(row.tax)
      } else {
        row.unTax = Number(row.otherIncomePrice)
      }
      row.unPrice = Number(row.otherIncomePrice) - Number(row.hasPrice)
    },
    change_tax(row) {
      if (row.otherIncomePrice > 0) {
        row.unTax = Number(row.otherIncomePrice) - Number(row.tax)
        row.unPrice = Number(row.otherIncomePrice) - Number(row.hasPrice)
      } else {
        row.unTax = 0
        row.unPrice = 0
      }
    },
    updateHasPrice(newVal) {
      if (newVal.length > 0) {
        newVal.filter((item, index) => {
          if (this.listData[index].unPrice <= 0 && this.listData[index].hasPrice > 0) {
            this.listData[index].unPrice = 0
            this.listData[index].status = '2'
          } else if (this.listData[index].unPrice > 0 && this.listData[index].hasPrice > 0) {
            this.listData[index].status = '1'
          } else if (this.listData[index].hasPrice <= 0) {
            this.listData[index].status = '0'
          }
        })
      }
    },
    getDictOptions() {
      getDictSelects('taxRateCode').then(res => {
        this.taxRateCodeList = res.data
      })
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.listData.length - 1) {
        return 'addRow'
      }
    },
    headerCellClassName(data) {
      if (['incomeName', 'otherIncomePrice', 'otherInTime'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    showDetail(data) {
      this.listData[this.currentIndex]['follows'] = data
      this.listData[this.currentIndex].hasPrice = data.map(item => item.price).reduce((accumulator, currentValue) => Number(accumulator) + Number(currentValue), 0)
      this.listData[this.currentIndex].unPrice = Number(this.listData[this.currentIndex].otherIncomePrice) - Number(this.listData[this.currentIndex].hasPrice)
    },
    setFileName(...data) {
      this.formData.orderFileName = data[0]
      this.formData.orderFileRealName = data[1]
      this.formData.orderUrl = data[2]
    },
    setFileName2(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    setFileName3(...data) {
      this.listData[data[3]].fileName = data[0]
      this.listData[data[3]].fileRealName = data[1]
      this.listData[data[3]].fileUrl = data[2]
    },
    addRow() {
      const obj = {
        status: '0',
        incomeName: '',
        otherIncomePrice: '',
        tax: '',
        unTax: '0',
        hasPrice: '0',
        unPrice: '0',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: '',
        // otherInTime: '',
        follows: []
      }
      this.listData.push(obj)
    },
    chooseOrders() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectionId: this.formData.saleOrderId ? this.formData.saleOrderId : ''
          } // props
        },
        area: ['1420px', '700px'],
        title: '选择销售订单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    showOrder(data) { // 选择销售订单的回调、
      this.formData.taxAllPrice = data.taxAllPrice
      this.formData.saleOrderCode = data.code
      this.formData.saleOrderId = data.id
      this.formData.orderFileName = data.fileName
      this.formData.orderFileRealName = data.fileRealName
      this.formData.orderUrl = data.url
      this.formData.saleCustomerId = data.saleCustomerId
      this.formData.accountName = data.accountName ? data.accountName : '暂无'
      this.formData.taxpayerNumber = data.taxpayerNumber ? data.taxpayerNumber : '暂无'
      this.formData.accountBank = data.accountBank ? data.accountBank : '暂无'
      this.formData.accountNumber = data.accountNumber ? data.accountNumber : '暂无'
      this.formData.invoicePhone = data.invoicePhone ? data.invoicePhone : '暂无'
      this.formData.invoiceAddress = data.invoiceAddress ? data.invoiceAddress : '暂无'
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
    },
    changeInvoicePrice(e, index) {
      this.listData[index].unPrice = Number(e) - Number(this.listData[index].hasPrice)
    },
    payOrder(row, index) {
      this.currentIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: followPay, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            row: row.follows
          }// props
        },
        area: ['880px', '350px'],
        title: '跟进收款', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    selectionChange(rows) {
      this.selectionsAll = rows
    },
    // 合计行
    getSummaries(param) {
      const {
        columns,
        data
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'otherIncomePrice':
            sums[index] = data.map(item => item.otherIncomePrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.otherIncomePrice = Number(sums[index])
            break
        }
        switch (column.property) {
          case 'unTax':
            sums[index] = data.map(item => item.unTax).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'tax':
            sums[index] = data.map(item => item.tax).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            break
        }
        switch (column.property) {
          case 'hasPrice':
            sums[index] = data.map(item => item.hasPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.hasPrice = Number(sums[index])
            break
        }
        switch (column.property) {
          case 'unPrice':
            sums[index] = data.map(item => item.unPrice).reduce((prev, curr) => {
              if (curr) {
                return new Big(prev).plus(curr).toString()
              } else {
                return new Big(prev).toString()
              }
            }, 0)
            this.formData.unPrice = Number(sums[index])
            break
        }
      })
      return sums
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.listData = res.data.details
        this.$nextTick(() => {
          this.loading = false
        })
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.listData.filter(item => !item.incomeName).length > 0) {
            this.$message.warning('收入名称不能为空')
            return
          }
          if (this.listData.some(item => item.otherIncomePrice && !this.SETTINGS.reg_no_zero.test(item.otherIncomePrice))) {
            this.$message.warning('附加收款金额未正确填写')
            return
          }
          if (this.listData.filter(item => !item.otherIncomePrice).length > 0) {
            this.$message.warning('附加收款金额不能为空')
            return
          }
          // if (this.listData.filter(item => !item.otherInTime).length > 0) {
          //   this.$message.warning('收款时间不能为空')
          //   return
          // }
          this.formData.details = this.listData
          this.formData.receiptTime = this.formData.receiptTime ? this.formData.receiptTime : moment(new Date()).format('YYYY-MM-DD')
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove(_this.id).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.$layer.close(_this.layerid) // 关闭弹框
          _this.$parent.getList()
        })
      }).catch(() => {})
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.isReject {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 27px;
  background-color: rgb(152,153,161);
  border-radius: 4px;
  font-size: 14px;
  color: #fff;
  padding: 0px;
  border: 1px solid rgb(152,153,161);
}
.pending_payment {
  color: #387bfc;
}
.under_execution {
  color:#FF9900;
}
.adequate_space {
  color: #19be6b;
}
.insufficient_space {
  color: rgb(231, 108, 108);
}
.insufficient_space2 {
  color: rgb(255, 151, 32);
}
.revoke_space {
  color: #999999;
}
/deep/.blueColor{
  color: #387bfc;
}
/deep/.blueColor:hover {
  cursor: pointer;
}
.main_bottom{
  justify-content:space-between !important;
}
/deep/ .el-table__fixed-footer-wrapper {
  .el-table__cell:last-of-type {
    height: 39px !important;
  }
}
.customer_info{
  margin-top: 15px;
}
.top_margin{
  margin-top: 40px !important;
}
/deep/ .el-tabs__header{
  margin: 0 !important;
}
///deep/ .el-tabs__content{
//  padding: 0 16px !important;
//}
.form_item{
  border-bottom: 1px solid #D6D6D6;
  // width: 100%;
  border-bottom: 1px solid #D6D6D6;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  /deep/ .el-form-item__label:before{
    content: none;
  }
  /deep/ .el-form-item__label{
    color: #1F51B3;
    font-size: 15px;
  }
  /deep/ .el-form-item__label{
    width: 140px !important;
    margin-top: 10px;
  }
  /deep/ .el-form-item__content{
    color: #333333;
    font-size: 15px;
    flex: 1;
    width: unset;
    margin-top: 10px;
    margin-right: 0px;
  }
}
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  padding-top:20px !important ;
  height: 100%;
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
///deep/ .el-table__footer-wrapper{
//  width: calc(100% - 8px);
//}

//// 滚动条的宽度
///deep/ .el-table__body-wrapper::-webkit-scrollbar {
//  width: 0px; // 横向滚动条
//}
///deep/ .el-table__body-wrapper {
//
//  width: calc(100% - 8px);
//}
//
////注意:hover
///deep/ .el-table__body-wrapper:hover::-webkit-scrollbar {
//  width: 8px; // 横向滚动条
//}
///deep/ .el-table__body-wrapper:hover{
//  width: 100%;
//}
.main_bottom_add{
  justify-content: flex-end !important;
}
.main_bottom_delete{
  .el-button{
    margin-left: 0;
  }
}
</style>
